import requests
from lxml import etree
import csv


class a(object):
    def __init__(self, num):
        self.count = num
        self.dicts = []
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36',
            'Cookie': 'antipas=73708905B898941f05O5f435; uuid=967332f2-20d1-4bc6-f8bb-b200466ae235; clueSourceCode=%2A%2300; ganji_uuid=6257258086354780448486; sessionid=dbb7f827-cfd1-4125-f7d5-f8c387f89b93; lg=1; close_finance_popup=2020-11-12; cainfo=%7B%22ca_a%22%3A%22-%22%2C%22ca_b%22%3A%22-%22%2C%22ca_s%22%3A%22seo_baidu%22%2C%22ca_n%22%3A%22default%22%2C%22ca_medium%22%3A%22-%22%2C%22ca_term%22%3A%22-%22%2C%22ca_content%22%3A%22-%22%2C%22ca_campaign%22%3A%22-%22%2C%22ca_kw%22%3A%22-%22%2C%22ca_i%22%3A%22-%22%2C%22scode%22%3A%22-%22%2C%22keyword%22%3A%22-%22%2C%22ca_keywordid%22%3A%22-%22%2C%22display_finance_flag%22%3A%22-%22%2C%22platform%22%3A%221%22%2C%22version%22%3A1%2C%22client_ab%22%3A%22-%22%2C%22guid%22%3A%22967332f2-20d1-4bc6-f8bb-b200466ae235%22%2C%22ca_city%22%3A%22nj%22%2C%22sessionid%22%3A%22dbb7f827-cfd1-4125-f7d5-f8c387f89b93%22%7D; user_city_id=12; _gl_tracker=%7B%22ca_source%22%3A%22-%22%2C%22ca_name%22%3A%22-%22%2C%22ca_kw%22%3A%22-%22%2C%22ca_id%22%3A%22-%22%2C%22ca_s%22%3A%22self%22%2C%22ca_n%22%3A%22-%22%2C%22ca_i%22%3A%22-%22%2C%22sid%22%3A31357962003%7D; cityDomain=bj; guazitrackersessioncadata=%7B%22ca_kw%22%3A%22-%22%7D; Hm_lvt_bf3ee5b290ce731c7a4ce7a617256354=1605140053,1605143715; preTime=%7B%22last%22%3A1605143721%2C%22this%22%3A1605140052%2C%22pre%22%3A1605140052%7D; Hm_lpvt_bf3ee5b290ce731c7a4ce7a617256354=1605143721'
        }

    def counts(self):
        c = 1
        for i in range(self.count):
            url = "https://www.guazi.com/bj/buy/h4/o%s/" % c
            responses = requests.get(url=url, headers=self.headers)
            c += 1
            html = etree.HTML(responses.text)
            title_href = html.xpath("//a[@class='car-a']")
            for i in title_href:
                title_text = i.xpath(".//h2[@class='t']/text()")
                title_p = i.xpath(".//div[@class='t-price']/p/text()")
                title_year = i.xpath(".//div[@class='t-i']/text()")
                if title_text:
                    self.dicts.append({'类型': title_text[0], '车龄': title_year[0], '价格': title_p[0] + '万'})

    def xie(self):
        with open("瓜子二手.csv", "w", encoding="utf-8") as f:
            headers = ["类型", "车龄", "价格"]
            csv_f = csv.DictWriter(f, headers)
            csv_f.writeheader()
            csv_f.writerows(self.dicts)


A = a(10)
A.counts()
A.xie()
